package com.speily.study.provider.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.speily.study.provider.entity.AccountA;
import com.speily.study.provider.mapper.AccountAMapper;
import com.speily.study.provider.rocketmq.TransactionProducer;
import com.speily.study.provider.service.AccountAService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

/**
 * @Auther: SPL
 * @Date: 2019-07-09 18:17
 * @Description: 账户
 */
@Service
@Slf4j
public class AccountAServiceImpl extends ServiceImpl<AccountAMapper, AccountA> implements AccountAService {

    @Autowired
    private AccountAMapper accountAMapper;

    @Autowired
    @Qualifier("transactionProducer")
    private TransactionProducer transactionProducer;



    @Transactional
    public void consume(BigDecimal m,Long accountId) throws MQClientException, UnsupportedEncodingException {

        //业务处理
        AccountA accountA = accountAMapper.selectById(accountId);
        accountA.setMoney(accountA.getMoney().subtract(m));
        accountAMapper.updateById(accountA);

        //使用RocketMq发送事物消息，即prepare消息。
        // 消息发送时会调用TransactionListenerImpl.executeLocalTransaction方法，和本地io操作处在同一事物内
        Message msg =
                new Message("Topic-Transaction", "Tag-Transaction", "KEY" ,
                        ("Hello RocketMQ ").getBytes("utf-8"));
        SendResult sendResult = transactionProducer.getProducer().sendMessageInTransaction(msg,null);
        System.out.println(sendResult.toString());



        log.info("======账户:{}；扣费：{}",accountA.getName(),m.toString());
    }
}
